import os
import json
from datetime import datetime
from config import RATINGS_STORAGE_FILE, USERS_DATA_DIR

# 从用户文件中加载特定电影的评分
def load_movie_ratings(movie_name):
    """从用户文件中加载特定电影的评分数据并计算平均分"""
    try:
        # 初始化评分累加器
        overall_sum = 0
        plot_sum = 0
        actors_sum = 0
        sound_sum = 0
        rating_count = 0
        
        # 检查用户数据目录是否存在
        if not os.path.exists(USERS_DATA_DIR):
            print(f"用户数据目录不存在: {USERS_DATA_DIR}")
            return {
                'overall': 0,
                'plot': 0,
                'actors': 0,
                'sound': 0,
                'count': 0
            }
        
        # 遍历所有用户文件
        for filename in os.listdir(USERS_DATA_DIR):
            if filename.endswith('.json'):
                user_file_path = os.path.join(USERS_DATA_DIR, filename)
                try:
                    with open(user_file_path, 'r', encoding='utf-8') as f:
                        user_data = json.load(f)
                        # 检查用户是否有该电影的评分
                        if 'ratings' in user_data and movie_name in user_data['ratings']:
                            movie_rating = user_data['ratings'][movie_name]
                            # 累加评分
                            overall_sum += movie_rating.get('overall', 0)
                            plot_sum += movie_rating.get('plot', 0)
                            actors_sum += movie_rating.get('actors', 0)
                            sound_sum += movie_rating.get('sound', 0)
                            rating_count += 1
                except Exception as e:
                    print(f"读取用户文件 {filename} 出错: {str(e)}")
                    continue
        
        # 计算平均分
        if rating_count > 0:
            return {
                'overall': round(overall_sum / rating_count, 1),
                'plot': round(plot_sum / rating_count, 1),
                'actors': round(actors_sum / rating_count, 1),
                'sound': round(sound_sum / rating_count, 1),
                'count': rating_count
            }
        else:
            # 如果没有评分记录，返回默认值
            return {
                'overall': 0,
                'plot': 0,
                'actors': 0,
                'sound': 0,
                'count': 0
            }
    except Exception as e:
        print(f"加载电影评分出错: {str(e)}")
        return {
            'overall': 0,
            'plot': 0,
            'actors': 0,
            'sound': 0,
            'count': 0
        }

# 获取当前电影的所有评分
def get_current_movie_ratings(video_filename):
    """获取当前电影的评分"""
    if video_filename:
        return load_movie_ratings(video_filename)
    
    # 如果没有当前视频，返回默认评分
    return {
        'overall': 0,
        'plot': 0,
        'actors': 0,
        'sound': 0,
        'count': 0
    }